package com.example.socialmediaplatform.controller;

import com.example.socialmediaplatform.model.DAOUser;
import com.example.socialmediaplatform.model.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user/password")
public class UserPasswordController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public static class PasswordChangeRequest {
        public String oldPassword;
        public String newPassword;
    }

    @PostMapping("")
    public ResponseEntity<?> changePassword(Authentication authentication, @RequestBody PasswordChangeRequest req) {
        String username = authentication.getName();
        List<DAOUser> users = userRepository.findByUsername(username);
        if (users.isEmpty()) {
            return ResponseEntity.status(404).body("用户不存在");
        }
        DAOUser user = users.get(0);
        if (!passwordEncoder.matches(req.oldPassword, user.getPassword())) {
            return ResponseEntity.status(400).body("原密码错误");
        }
        user.setPassword(passwordEncoder.encode(req.newPassword));
        userRepository.save(user);
        return ResponseEntity.ok("密码修改成功");
    }
} 
